<template>
  <view v-if="isToken" class="container">
    <span class="banbenhao-dianhua" @click="showActionSheet('18947472919')">
      {{ storedVersion ? '当前版本：V' + storedVersion + '|' : '' }}
      📞值班电话：18947472919</span
    >
    <uni-nav-bar
      :border="false"
      statusBar
      leftWidth="0"
      backgroundColor="transparent"
    >
      <view class="leftHeader">
        <text
          class="login"
          @click="onLocation('/pages/login/index')"
          v-if="!isToken"
          >登录</text
        >
        <text v-else>国源公司后勤智慧园区</text>
      </view>
      <template #right>
        <uni-badge
          v-if="
            getMenuItem('message') && getMenuItem('message').selectStatus == 1
          "
          :is-dot="true"
          :text="isMsg"
          :offset="[6, 2]"
          absolute="rightTop"
        >
          <uni-icons
            type="notification-filled"
            size="24"
            color="#44A5F4"
            @click="onLocation('/pages/notice/list')"
          >
          </uni-icons>
        </uni-badge>
      </template>
    </uni-nav-bar>

    <view class="oneBox">
      <image class="bgImg" src="/static/image/banner1.png" />
      <view class="text">
        <view class="name">国源公司 智慧园区</view>
        <view class="tips">请使用“扫一扫”，访问相关内容</view>
      </view>
      <button
        class="btn"
        type="primary"
        @click="$noMultipleClicks(onAction, 1)"
      >
        扫一扫
      </button>
    </view>

    <view class="twoBox">
      <view
        class="item"
        v-if="getMenuItem('patrol') && getMenuItem('patrol').selectStatus == 1"
        @click="onLocation('/pages/patrol/list')"
      >
        <view class="pic">
          <image class="img" src="/static/image/img0.png" />
        </view>
        <view class="text">{{ getMenuItem('patrol').menuXcxName }}</view>
      </view>
      <view
        class="item"
        v-if="
          getMenuItem('workOrder') && getMenuItem('workOrder').selectStatus == 1
        "
        @click="onLocation('/pages/workOrder/list')"
      >
        <view class="pic">
          <image class="img" src="/static/image/img1.png" />
        </view>
        <view class="text">{{ getMenuItem('workOrder').menuXcxName }}</view>
      </view>
      <view
        class="item"
        v-if="
          getMenuItem('security') && getMenuItem('security').selectStatus == 1
        "
        @click="onLocation('/pages/security/index')"
      >
        <view class="pic">
          <image class="img" src="/static/image/img2.png" />
        </view>
        <view class="text">{{ getMenuItem('security').menuXcxName }}</view>
      </view>
      <!-- <view class="item" @click="onLocation('/pages/alarm/safe')">
        <view class="pic">
          <image class="img" src="/static/image/img2.png" />
        </view>
        <view class="text">安防告警</view>
      </view> -->
      <view
        class="item"
        v-if="
          getMenuItem('facilityRepair') &&
          getMenuItem('facilityRepair').selectStatus == 1
        "
        @click="onLocation('/pages/facilityRepair/index')"
      >
        <view class="pic">
          <image class="img" src="/static/image/img3.png" />
        </view>
        <view class="text">{{
          getMenuItem('facilityRepair').menuXcxName
        }}</view>
      </view>
    </view>

    <view class="thrBox">
      <!-- <view
        class="item l"
        v-if="!isToken"
        @click="
          onLocation(
            '/pages/visitor/h5/invitation?type=2&work=work_visitor_prebook'
          )
        "
      >
        <view class="text">访客预约</view>
        <view class="btn">去查看</view>
      </view> -->
      <view
        class="item l"
        v-if="
          getMenuItem('visitorPrebook') &&
          getMenuItem('visitorPrebook').selectStatus == 1
        "
        @click="
          onLocation(
            '/pages/visitor/invitation?type=2&work=work_visitor_prebook'
          )
        "
      >
        <view class="text">{{
          getMenuItem('visitorPrebook').menuXcxName
        }}</view>
        <view class="btn">去查看</view>
      </view>
      <view
        class="item r"
        v-if="
          getMenuItem('visitorInvite') &&
          getMenuItem('visitorInvite').selectStatus == 1
        "
        @click="
          onLocation(
            '/pages/visitor/invitation?type=1&work=work_visitor_invite'
          )
        "
      >
        <view class="text">{{ getMenuItem('visitorInvite').menuXcxName }}</view>
        <view class="btn">去查看</view>
      </view>
    </view>

    <view class="forBox">
      <uni-section title="管理中心" type="line" />
      <view class="list" v-if="menuShowList.length">
        <view
          class="item"
          v-for="(v, i) in menuShowList"
          :key="i"
          @click="onLocation(v.path)"
        >
          <image class="quote" src="/static/image/icon_quote.png" />
          <view class="name">
            <view class="text">{{ v.menuXcxName }}</view>
            <image class="arrow" src="/static/image/icon_circle_arrow.png" />
          </view>
          <view class="btn">去查看</view>
        </view>

        <!-- <view class="item" @click="onLocation('/pages/dish/index')">
          <image class="quote" src="/static/image/icon_quote.png" />
          <view class="name">
            <view class="text">食堂饭菜售价等信息审批公示</view>
            <image class="arrow" src="/static/image/icon_circle_arrow.png" />
          </view>
          <view class="btn">去查看</view>
        </view> -->
        <!-- <view class="item" @click="onDev">
          <image class="quote" src="/static/image/icon_quote.png" />
          <view class="name">
            <view class="text">实时监控</view>
            <image class="arrow" src="/static/image/icon_circle_arrow.png" />
          </view>
          <view class="btn">去查看</view>
        </view>
        <view class="item" @click="onDev">
          <image class="quote" src="/static/image/icon_quote.png" />
          <view class="name">
            <view class="text">监控回放</view>
            <image class="arrow" src="/static/image/icon_circle_arrow.png" />
          </view>
          <view class="btn">去查看</view>
        </view> -->
      </view>
    </view>

    <view class="footer">
      <view class="line" />
      <view>我也是有底线的</view>
      <view class="line" />
    </view>
  </view>
</template>

<script>
import _ from 'lodash';
import { getUnread } from '@/api/notice';
import { latestVersion } from '@/api/index';
const menuList = [
  // 物品放行
  {
    label: 'passPermit',
    path: '/pages/passPermit/index',
  },
  // 矿灯管理
  {
    label: 'light',
    path: '/pages/light/list',
  },
  // 更衣柜管理
  {
    label: 'locker',
    path: '/pages/locker/list',
  },
  // 巡更记录
  {
    label: 'patrolStaff',
    path: '/pages/patrol/staff/list',
  },
  // 值班记录
  {
    label: 'dutyRecord',
    path: '/pages/dutyRecord/index',
  },
  // 零星保修
  {
    label: 'repairService',
    path: '/pages/repairService/index',
  },
  // 房间管理
  {
    label: 'room',
    path: '/pages/room/list',
  },
  // 公寓检查
  {
    label: 'roomCheck',
    path: '/pages/room/checkList',
  },
  // 菜品管理
  {
    label: 'prod',
    path: '/pages/repast/partnerProd',
  },
  // 每日菜单
  {
    label: 'partnerDailyMenu',
    path: '/pages/repast/partnerDailyMenu',
  },
  // 食品留样
  {
    label: 'restaurantDishRecord',
    path: '/pages/repast/restaurantDishRecord',
  },
  // 食堂饭菜售价等信息审批公示
  {
    label: 'foodsApproval',
    path: '/pages/dish/index',
  },
  // 消费记录
  {
    label: 'consumptionRecord',
    path: '/pages/repast/consumptionRecord',
  },
  // 一卡通
  {
    label: 'partnerCard',
    path: '/pages/repast/partnerCard',
  },
  // 身体质量指数BMI
  {
    label: 'bmi',
    path: '/pages/repast/bmi',
  },
];
export default {
  components: {},
  data() {
    return {
      isMsg: 0,
      menu: uni.getStorageSync('menu') || [],
      isToken: !!uni.getStorageSync('token'),
      // 重复点击，使用noMultipleClicks方法时，需要在当前页面创建此变量
      noClick: true,
      menuShowList: [],
      storedVersion: uni.getStorageSync('appVersion'),
    };
  },
  onLoad(query) {
    // // 扫码
    // if (query.q) {
    //   // 解码
    //   let path = decodeURIComponent(query.q);
    //   this.scan(path);
    // }

    // 初始化存储版本（优先使用本地存储的版本）
    this.storedVersion = uni.getStorageSync('appVersion') || '1.0.0';

    // 获取当前应用版本
    plus &&
      plus.runtime.getProperty(plus.runtime.appid, (info) => {
        const currentVersion = info.version;

        // 版本不一致时更新存储
        if (this.compareVersions(currentVersion, this.storedVersion)) {
          this.clearCache();
          uni.setStorageSync('appVersion', currentVersion);
          this.storedVersion = currentVersion;
        }

        // 确保在此回调内获取最新版本
        this.getLatestVersion();
      });

    this.menuShowList = [];
    menuList.forEach((v) => {
      const item = this.$util.getMenuItem(v.label);
      if (item && item.selectStatus == 1) {
        this.menuShowList.push({ ...v, ...item });
      }
    });
    if (Object.keys(query).length) {
      // 解码
      // let path = decodeURIComponent(query);
      let path = query;
      this.scan(path);
    }
  },
  onShow() {
    if (this.isToken) {
      this.getData();
    }
    //  else {
    //   uni.navigateTo({ url: '/pages/login/index' });
    // }
    if (!this.menuShowList.length) {
      menuList.forEach((v) => {
        const item = this.$util.getMenuItem(v.label);
        if (item && item.selectStatus == 1) {
          this.menuShowList.push({ ...v, ...item });
        }
      });
    }
  },
  methods: {
    clearCache() {
      // 清理逻辑（参考方法一的实现）
      if (plus.os.name === 'Android') {
        let main = plus.android.runtimeMainActivity();
        let cacheDir = main.getCacheDir();
        let files = plus.android.invoke(cacheDir, 'listFiles');
        files.forEach((file) => {
          let filePath = '' + file;
          plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
            if (entry.isDirectory) {
              entry.removeRecursively(); // 递归删除子目录
            } else {
              entry.remove();
            }
          });
        });
      } else {
        plus.cache.clear(); // iOS/H5 清理缓存
      }
    },
    // 正确的版本比较方法（支持多级版本号）
    compareVersions(v1, v2) {
      const v1Parts = v1.split('.').map(Number);
      const v2Parts = v2.split('.').map(Number);

      for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
        const part1 = v1Parts[i] || 0;
        const part2 = v2Parts[i] || 0;
        if (part1 !== part2) {
          return part1 > part2;
        }
      }
      return false; // 版本相等
    },

    getLatestVersion() {
      latestVersion()
        .then(({ data }) => {
          if (!data?.appVersion) return;

          // 使用正确的比较方法
          if (this.compareVersions(data.appVersion, this.storedVersion)) {
            uni.showModal({
              title: '更新提示',
              content: '发现新版本，是否立即更新？',
              confirmText: '去更新',
              showCancel: false,
              success: (res) => {
                if (res.confirm) {
                  this.handleUpdate(data.downloadAddress);
                }
              },
            });
          }
        })
        .catch(console.error);
    },

    handleUpdate(downloadUrl) {
      if (!downloadUrl) {
        uni.showToast({ icon: 'none', title: '下载地址错误，请联系管理员' });
        return;
      }

      plus.runtime.openURL(downloadUrl, (err) => {
        uni.showToast({ title: '跳转失败:' + err.message, icon: 'none' });
      });
    },
    // 数据
    getData() {
      getUnread().then((res) => {
        this.isMsg = res.data ? 1 : 0;
      });
    },
    // 扫码
    scan(path) {
      console.log('path', path);
      // 提示
      uni.showToast({
        icon: 'none',
        title: `扫码获取信息中...`,
        duration: 5000,
      });
      // 情况判断
      if (path) {
        uni.hideToast();
        this.onLocation(`/${path}`);
      } else {
        uni.hideToast();
        this.onAction(1);
      }
    },
    // 操作按钮
    onAction(e) {
      if (e) {
        /* #ifdef H5 */
        uni.showToast({
          icon: 'none',
          title: `H5页面不支持扫码功能`,
          duration: 5000,
        });
        /* #endif */
        /* #ifndef H5 */
        // 只允许通过相机扫码
        uni.scanCode({
          onlyFromCamera: true,
          success: (res) => {
            console.log('条码类型：', res.scanType);
            console.log('条码内容：', res.result);
            // 取path
            let path;
            if (
              res.scanType == 'WX_CODE' &&
              ['scanCode:ok'].includes(res?.errMsg)
            ) {
              path = res.path;
            } else if (res.scanType == 'QR_CODE') {
              path = res.result;
            }
            this.scan(path);
          },
        });
        /* #endif */
      } else {
      }
    },
    // 菜单数据
    getMenuItem(code) {
      let r = this.menu.filter((item) => item.menuXcxNo === code);
      return r.length === 0 ? null : r[0];
    },
    // 跳转页面
    onLocation(url) {
      uni.navigateTo({
        url,
      });
    },
    // 测试
    onDev() {
      uni.showToast({
        icon: 'none',
        title: '功能开发中',
        duration: 2000,
      });
    },
    // 显示操作菜单
    showActionSheet(phoneNumber) {
      uni.showActionSheet({
        itemList: ['呼叫', '复制'],
        success: (res) => {
          const index = res.tapIndex;
          if (index === 0) {
            this.makePhoneCall(phoneNumber);
          } else if (index === 1) {
            this.copyToClipboard(phoneNumber);
          }
        },
        fail: () => {
          // 用户点击了取消
        },
      });
    },

    // 拨打电话
    makePhoneCall(phoneNumber) {
      uni.makePhoneCall({
        phoneNumber: phoneNumber.toString(),
        success: () => {
          console.log('成功调起拨号面板');
        },
        fail: (err) => {
          console.error('拨打电话失败:', err);
        },
      });
    },

    // 复制到剪贴板
    copyToClipboard(text) {
      uni.setClipboardData({
        data: text.toString(),
        success: () => {
          uni.showToast({
            title: '复制成功',
            icon: 'none',
          });
        },
        fail: (err) => {
          console.error('复制失败:', err);
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: calc(100vh - var(--window-bottom) - 60rpx);
  padding-top: calc(var(--window-top));
  padding-bottom: calc(var(--window-bottom) + 60rpx);
  background: linear-gradient(180deg, #d7e4fd 0%, #fff 50%);
  position: relative;

  .banbenhao-dianhua {
    position: fixed;
    bottom: 10rpx;
    right: 40rpx;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.5);
    font-style: italic;
    z-index: 999;
  }
  // #ifdef MP-WEIXIN
  :deep(.uni-navbar__header-btns-right) {
    position: relative;
    right: 100px;
  }

  // #endif
  .login {
    font-size: 28rpx;
    color: #ffffff;
    padding: 10rpx 24rpx;
    background: #478cff;
    border-radius: 62rpx;
  }

  .oneBox {
    height: 276rpx;
    margin: 18rpx 36rpx 32rpx;
    padding: 0 40rpx;
    // background-image: url('~@/static/image/banner1.png');
    // background-repeat: no-repeat;
    // background-size: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    position: relative;
    z-index: 1;

    .bgImg {
      width: 100%;
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      z-index: -1;
    }

    .text {
      .name {
        color: #ffffff;
        font-size: 36rpx;
        font-weight: 600;
        line-height: 42rpx;
      }

      .tips {
        font-size: 26rpx;
        color: rgba(255, 255, 255, 0.7);
        line-height: 30rpx;
        padding-top: 10rpx;
      }
    }

    .btn {
      width: 158rpx;
      height: 52rpx;
      font-size: 28rpx;
      color: #2e61c1;
      line-height: 52rpx;
      margin: 36rpx 0 0;
      background: #d4e3f9;
      border-radius: 8rpx 8rpx 8rpx 8rpx;
    }
  }

  .twoBox {
    margin: 0rpx 62rpx;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .item {
      width: calc(25% - 0rpx);
      margin-bottom: 20rpx;

      .pic {
        width: 100rpx;
        height: 100rpx;
        margin: 0 auto 8rpx;

        .img {
          width: 100%;
          height: 100%;
        }
      }

      .text {
        font-size: 24rpx;
        color: #484848;
        line-height: 28rpx;
        text-align: center;
      }
    }
  }

  .thrBox {
    margin: 20rpx 36rpx 40rpx;
    display: flex;
    justify-content: space-between;

    .l {
      background-image: url('/static/image/visitor_bg0.png');
      background-size: 100% 100%;

      .btn {
        background: #62bfad;
      }
    }

    .r {
      background-image: url('/static/image/visitor_bg1.png');
      background-size: 100% 100%;

      .btn {
        background: #44a5f4;
      }
    }

    .item {
      width: calc(50% - 89rpx);
      padding: 28rpx 36rpx;
      display: flex;
      align-items: start;
      flex-direction: column;

      .btn {
        font-size: 20rpx;
        color: #ffffff;
        padding: 6rpx 16rpx;
        margin-top: 18rpx;
        border-radius: 68rpx 74rpx 0rpx 68rpx;
      }

      .text {
        color: #333333;
        font-size: 36rpx;
        font-weight: 600;
        line-height: 42rpx;
      }
    }
  }

  .forBox {
    margin: 0 36rpx;

    :deep(.uni-section) {
      background-color: transparent;

      .uni-section-header {
        padding: 0 0 36rpx;

        .uni-section-header__content {
          font-weight: 600;
        }
      }
    }

    .list {
      display: flex;
      flex-wrap: wrap;

      .item {
        width: calc(33.333% - 48rpx);
        height: 206rpx;
        margin-right: 24rpx;
        margin-bottom: 24rpx;
        padding: 0 16rpx;
        display: flex;
        flex-direction: column;
        justify-content: center;

        &:nth-child(3n) {
          margin-right: 0;
        }

        &:nth-child(1),
        &:nth-child(4),
        &:nth-child(7),
        &:nth-child(10),
        &:nth-child(13),
        &:nth-child(16) {
          background-image: url('/static/image/color_bg0.png');
          background-size: 100% 100%;

          .btn {
            color: #b5cd9a;
          }
        }

        &:nth-child(2),
        &:nth-child(5),
        &:nth-child(8),
        &:nth-child(11),
        &:nth-child(14),
        &:nth-child(17) {
          background-image: url('/static/image/color_bg1.png');
          background-size: 100% 100%;

          .btn {
            color: #cdb798;
          }
        }

        &:nth-child(3),
        &:nth-child(6),
        &:nth-child(9),
        &:nth-child(12),
        &:nth-child(15),
        &:nth-child(18) {
          background-image: url('/static/image/color_bg2.png');
          background-size: 100% 100%;

          .btn {
            color: #97acc7;
          }
        }

        .quote {
          width: 26rpx;
          height: 24rpx;
          margin-left: 4rpx;
        }

        .name {
          padding: 12rpx 0;
          display: flex;
          align-items: center;

          .text {
            font-size: 28rpx;
            color: rgba(255, 255, 255, 0.9);
            line-height: 33rpx;
            flex: 1;
          }

          .arrow {
            width: 22rpx;
            height: 22rpx;
            margin-left: 6rpx;
          }
        }

        .btn {
          width: 88rpx;
          font-size: 20rpx;
          text-align: center;
          padding: 6rpx 0;
          margin: 0 6rpx;
          background: #ffffff;
          border-radius: 4rpx;
        }
      }
    }
  }
}

.footer {
  color: rgba(0, 0, 0, 0.3);
  font-size: 20rpx;
  font-weight: bold;
  line-height: 20rpx;
  padding: 20rpx 0;
  display: flex;
  align-items: center;
  justify-content: space-around;
  position: absolute;
  left: 40rpx;
  right: 40rpx;
  bottom: calc(var(--window-bottom) + 30rpx);

  .line {
    flex: auto;
    height: 2rpx;
    background: #dfdfdf;

    &:first-child {
      margin-right: 15rpx;
    }

    &:last-child {
      margin-left: 15rpx;
    }
  }
}

@media screen and (min-width: 961px) {
  .container {
    min-height: calc(100% - var(--window-bottom) - 60rpx);
  }
}
</style>
